﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.Web;

namespace Wassrile.Dialogs
{
    public partial class TokenAuth : Form
    {
        static string PRIVKEY = "uFpThveRscDMD6u4mhJdC1zP8Q4kvY7k";
        static string APPKEY = "kVeFXLTeiLgAKux9aHJicSC9c4QFsXGp";
        static string NAVIGATEURI = "http://wassr.jp/auth/?app_key={0}&sig={1}";
        static string HOST = "example.com";
        
        public string Token { get; private set; }

        public TokenAuth()
        {
            InitializeComponent();
            browser.StatusTextChanged += new EventHandler(browser_StatusTextChanged);
        }

        public string CreateSignature(string value)
        {
            var sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(PRIVKEY), true);
            try
            {
                string ret = BitConverter.ToString(sha1.ComputeHash(Encoding.ASCII.GetBytes(value)));
                return ret.Replace("-", String.Empty).ToLower();
            }
            catch (Exception e)
            {
                Krilib.Bridge.DebugReporter.AddReport(e);
                MessageBox.Show("Unknown error was occured - " + e.Message, "Signature Compute Failed", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return String.Empty;
            }
            finally
            {
                sha1.Clear();
            }
        }

        private void TokenAuth_Shown(object sender, EventArgs e)
        {
            browser.Navigate(String.Format(NAVIGATEURI, APPKEY, CreateSignature("app_key" + APPKEY)));
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        void browser_StatusTextChanged(object sender, EventArgs e)
        {
            StatusLabel.Text = browser.StatusText;
        }

        private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.Host == HOST)
            {
                //passed
                NameValueCollection collection = HttpUtility.ParseQueryString(e.Url.Query);
                string token = collection["token"];
                string hmac = collection["hmac"];

                if (hmac == CreateSignature("token" + token))
                {
                    Token = token;
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("Token validation error.", "token validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    this.DialogResult = DialogResult.Cancel;
                }
                this.Close();
            }
        }
    }
}
